<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function distributor_add_page() {
    return drupal_get_form('distributor_edit_form');
}

function distributor_edit_page($id) {
    return drupal_get_form('distributor_edit_form', $id);
}

function distributor_account_page() {
    global $user;
    return drupal_get_form('distributor_edit_form', $user->uid);
}
function distributor_upgrade_page() {
    global $user;
    $user_info = _get_user_info($user->uid);
    $employee_roles = array('administrator',  '销售员', '销售管理员', '农化管理员', '农化服务员','公司领导');
    $farmer_roles = array('农户','升级成农户');
    if($user_info['role'] == "authenticated user"){
        $role_result = user_role_load_by_name('升级成经销商');
        $new_user = array(
            'signature_format' => 'filtered_html',
            'status' => 1,
            'language' => 'zh-hans',
            'timezone' => 'Asia/Shanghai',
            'roles' => array(
                $role_result->rid =>  '升级成经销商',
            ),
        );
        $account = user_save($user, $new_user);
        drupal_static_reset("user_access");
        $user_info = _get_user_info($user->uid);
    }else if(in_array($user_info['role'],$employee_roles)||in_array($user_info['role'],$farmer_roles)){
        drupal_goto('/user');
    }
    insertDefaultDistributor($user->uid);
    return drupal_get_form('distributor_edit_form',$user->uid);
}

function distributor_edit_form($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : 0;
    if (!empty($id)) {
        $user_info = _get_user_info($user->uid);
        if($user_info['role'] === '经销商'){//农户只能查看修改自己的信息,其他角色通过“权限”控制页面控制
            $id = $user->uid;
            $form_state['build_info']['args'][0] = $id;
        }
        $account = user_load($id);
        $form_state['account'] = $account;
        $record = nonghua_data_load('distributor', 'distributor_id', $id);
        if (empty($account)&&empty($record)) {
            drupal_set_message(t('经销商不存在！'), 'status', FALSE);
            return $form;
        }
        $form_state['update'] = true;
        $form_state['id'] = $id;
    }else{
        $form_state['insert'] = true;
    }
    // 判断用户角色
    if (!nonghua_user_access('distributor', 'view', $id, !empty($record) ? $record->author_uid : 0, $id)) {
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }

    $form['distributor'] = array(
//        '#type' => 'fieldset',
//        '#title' => '基本信息',
//        '#collapsed' => false,
//        '#collapsible' => true,
    );

    $form['distributor']['name'] = array(
        '#type' => 'textfield',
        '#title' => '经销商名称',
        '#size' => 32,
        '#maxlength' => 32,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->distributor_name:'',
    );

    if (empty($record)) {
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE, '','省必填');
    } else {
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE, $record->addr_id,'省必填');
    }

    $form['distributor']['details'] = array(
        '#type' => 'textfield',
        '#title' => '详细地址',
        '#default_value' => !empty($record) ? $record->addr_details : '',
        '#size' => 50,
        '#maxlength' => 50,
    );
    $inout_options = array('关内' => '关内', '关外' => '关外');
    $form['distributor']['inorout'] = array(
        '#type' => 'radios',
        '#title' => '关内/关外',
        '#default_value' => !empty($record) ? $record->inorout:'关内',
        '#options' => $inout_options,
    );

    $form['distributor']['phone'] = array(
        '#type' => 'textfield',
        '#title' => '电话号码（例如：010 12345678  或者 010-12345678 或者 010--12345678）',
        '#size' => 32,
        '#maxlength' => 15,
        '#required' => FALSE,
        '#default_value' => !empty($record) ? $record->phone:'',
    );

    $form['distributor']['cell'] = array(
        '#type' => 'textfield',
        '#title' => '手机号码',
        '#size' => 32,
        '#maxlength' => 15,
        '#default_value' => !empty($record) ? trim($record->cell):'',
    );

    $form['distributor']['email'] = array(
        '#type' => 'textfield',
        '#title' => '电子邮件',
        '#size' => 32,
        '#maxlength' => 40,
        '#default_value' => !empty($record) ? $record->email:'',
    );
    $form['distributor_login'] = array(
//        '#type' => 'fieldset',
//        '#title' => '登录信息',
//        '#collapsed' => true,
//        '#collapsible' => true,
    );
//    $form['distributor_login']['account'] = array(
//        '#type' => 'textfield',
//        '#title' => t('用户登录名'),
//        '#maxlength' => USERNAME_MAX_LENGTH,
////        '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
//        '#required' => TRUE,
//        '#disabled' => !empty($account)?true:false,
//        '#attributes' => array('class' => array('username')),
//        '#default_value' => !empty($account)?$account->name:'',
//    );
    $form['distributor_work'] = array(
//        '#type' => 'fieldset',
//        '#title' => '工作信息',
//        '#collapsed' => TRUE,
//        '#collapsible' => true,
    );
    $distributor_options['0'] = '无上级经销商';
    $distributors = db_select('distributor', 'D')
        -> fields('D',array('distributor_id', 'distributor_name'))
        -> condition('distributor_id', $id, '<>')
        -> execute();
    foreach ($distributors as $distributor) {
        $distributor_options[$distributor->distributor_id] = $distributor->distributor_name;
    }
    $form['distributor_work']['parent'] = array(
        '#type' => 'select',
        '#title' =>  '上级经销商',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $distributor_options,
        '#default_value' => !empty($record) ? $record->parent_distributor_id:'',
    );
//    if (empty($record)) {
//        _insert_juris_selection_form($form, '', 'distributor');
//    } else {
//        _insert_juris_selection_form($form, $record->juris_id, 'distributor');
//    }



    $form['distributor_other'] = array(
//        '#type' => 'fieldset',
//        '#title' => '备注信息',
//        '#collapsed' => TRUE,
//        '#collapsible' => true,
    );
    $form['distributor_other']['comments'] = array(
        '#type' => 'textarea',
        '#title' => '备注',
        '#size' => 32,
        '#cols' => 1,
        '#maxlength' => 50,
        '#default_value' => !empty($record) ? $record->comments:'',
        '#attributes'=> array('placeholder' => "联系人：张春富"),

    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
        '#access' => nonghua_user_access('distributor', 'edit', $id, !empty($record) ? $record->author_uid:0,$id)
    );
    return $form;
}

function distributor_edit_form_validate($form, &$form_state) {
    global $user;
    $user_info = _get_user_info();
    pregPN_E_TP($form_state['values']['cell'],$form_state['values']['phone'],$form_state['values']['email']);
    _address_element_validate($form_state);

    if(isset($form_state['insert']) && $form_state['insert'] ) {
        if (isset($form_state['values']['account'])&&!empty($form_state['values']['account'])) {
            if ($error = user_validate_name($form_state['values']['account'])) {
                form_set_error('account', $error);
            }
            elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('name', db_like($form_state['values']['account']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
                form_set_error('account', t('The name %name is already taken.', array('%name' => $form_state['values']['account'])));
            }
        }

        if (empty($form_state['values']['account'])) {
            $record = db_select('users', 'u')
                ->condition('u.name', $form_state['values']['cell'])
                ->fields('u')
                ->execute()->fetchAssoc();
            if (!empty($record)) {
                form_set_error('cell', "利用该手机号作为登录名，该手机号已存在！");
            }
        }
    }
}

function distributor_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    if ($form_state['values']['parent'] != 0) { // to-do: 考虑上级经销商修改/删除情况，会影响下级所有经销商level和parent字段
        $parent = nonghua_data_load('distributor', 'distributor_id',$form_state['values']['parent']);
        $level = $parent->level + 1;
    } else {
        $level = 1;
    }
    $user_info = _get_user_info();
    $transaction = db_transaction();
    try {
        clear_search_autocomplete_cach();
        if (empty($id)) { //add new distributor

            $role_result = user_role_load_by_name('经销商');
            $new_user = array(
                'name' => !empty($form_state['values']['name']) ? $form_state['values']['name'] : $form_state['values']['cell'],
                'pass' => '123456',
                'mail' => $form_state['values']['email'],
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' => $form_state['values']['email'],
                'roles' => array(
                    $role_result->rid => '经销商',
                ),
            );

            $account = user_save('', $new_user);


            $nid = db_insert('distributor')// Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'distributor_id' => $account->uid,
                'distributor_name' => trim($form_state['values']['name']),
                'parent_distributor_id' => $form_state['values']['parent'],
                'level' => $level,
                'addr_details' => $form_state['values']['details'],
                'inorout' => $form_state['values']['inorout'],
                'phone' => $form_state['values']['phone'],
                'cell' => $form_state['values']['cell'],
                'email' => $form_state['values']['email'],
                'comments' => $form_state['values']['comments'],
                'status'=>'经销商',
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            drupal_goto('distributor/list');
        } else {
            $new_user = array(
//                'name' => !empty($form_state['values']['account']) ? $form_state['values']['account'] : $form_state['values']['cell'],
//                'pass' => !empty($form_state['values']['pass']) ? $form_state['values']['pass'] : '123456',
                'mail' => $form_state['values']['email'],
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' => $form_state['values']['email'],
            );
            $account = $form_state['account'];
            user_save($account, $new_user);

            $nid = db_update('distributor')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'addr_id' => $address,
                'distributor_name' => trim($form_state['values']['name']),
                'parent_distributor_id' => $form_state['values']['parent'],
                'level' => $level,
                'addr_details' => $form_state['values']['details'],
                'inorout' => $form_state['values']['inorout'],
                'phone' => $form_state['values']['phone'],
                'cell' => $form_state['values']['cell'],
                'email' => $form_state['values']['email'],
                'comments' => $form_state['values']['comments'],
                'timestamp' => time(),))
                ->condition('distributor_id', $id, '=')
                ->execute();
//            drupal_goto('distributor/list');
            drupal_set_message(t('修改成功！'), 'status', FALSE);
            if($user_info['role'] === '经销商' && $user->uid === $id){
                drupal_goto('distributor/edit/'.$user->uid,['query'=>['distributor_id'=>$user->uid]]);
            }
            if($user_info['role'] === '升级成经销商'){
                drupal_goto('account/upgrade/result/1');
            }
            drupal_goto('distributor/list');
        }
    }catch (Exception $e) {
        $transaction->rollback();
        watchdog_exception('user', $e);
        if( $user_info['role'] == "升级成经销商"){
            drupal_goto('account/upgrade/result/0');
        }
        drupal_set_message(t('操作失败！ '.$e->getMessage()), 'error', FALSE);
    }
}
function insertDefaultDistributor($distributor_id){
    global $user;
    $record = nonghua_data_load('distributor', 'distributor_id', $distributor_id);
    if(empty($record)){
        $nid = db_insert('distributor')// Table name no longer needs {}
        ->fields(array(
            'addr_id' => 3925,
            'distributor_id' => $distributor_id,
            'distributor_name' => " ",
            'parent_distributor_id' => 0,
            'level' => 1,
            'addr_details' => "",
            'inorout' => "关内",
            'phone' => "",
            'cell' => " ",
            'email' =>null,
            'comments' => "",
            'status' => "升级成经销商",
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
    }
}